import type { CSSProperties } from 'vue'
import { useScrollInjection } from '@/utils/composition/useScroll'

type ColorTransitionOptions = {
  boundaryHeight: number
  colorVector: [number, number, number] // RGB
}

/**
 * 根据滚动高度计算背景色透明度
 * 【使用时需要在Page上调用"useScrollProvider"以注入高度数据】
 */
export function useColorTransition(options: ColorTransitionOptions): { transitionRef: Ref<CSSProperties> } {
  const { boundaryHeight, colorVector } = options
  const { scrollTopRef } = useScrollInjection()
  const styleRef = ref<CSSProperties>({
    backgroundColor: _utils.getStyleByRGBA(colorVector, 0),
  })
  watch(
    () => scrollTopRef.value,
    (scrollTop) => {
      const opacity = scrollTop >= boundaryHeight ? 1 : scrollTop / boundaryHeight
      styleRef.value.backgroundColor = _utils.getStyleByRGBA(options.colorVector, opacity)
    }
  )

  return { transitionRef: styleRef }
}

const _utils = {
  getStyleByRGB(rgbVector: [number, number, number]) {
    return `rgb(${rgbVector.join(', ')})`
  },
  getStyleByRGBA(rgbVector: [number, number, number], alpha: number) {
    return `rgba(${rgbVector.join(', ')}, ${alpha})`
  },
}
